package mirfordevoservice.system.listener;

import java.net.Socket;
import java.util.Timer;
import java.util.TimerTask;

import static mirfordevoservice.system.contasnt.GameConstant.GameSession.ONLINE_HUMAN_SESSION;
import static mirfordevoservice.system.contasnt.GameConstant.GameSession.ONLINE_ROLE_SESSION;

/**
 * Created by Heart!
 *
 * @Author ZhangChaoJian
 * @Date ${Date}-11:48
 * Wants More Then Try Hard More!
 */
public class SocketAliveWatcher implements Runnable {
    private static SocketAliveWatcher ourInstance = new SocketAliveWatcher();

    public static SocketAliveWatcher getInstance() {
        System.out.println("监听服务器会话...");
        return ourInstance;
    }

    private SocketAliveWatcher() {
    }


    /**
     * 无效会话将每5秒剔除
     */
    @Override
    public void run() {
        Timer timer = new Timer("socketListener", true);
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                socketWatcherRun();
            }
        }, 0, 5000);
    }

    /**
     * 会话监听开启
     */
    private void socketWatcherRun() {
        for (Socket socket : ONLINE_ROLE_SESSION.keySet()) {
            if (socket == null || socket.isClosed()) {
                /**
                 * 失效的socket剔除会话集合
                 */
                long id = ONLINE_ROLE_SESSION.get(socket);
                ONLINE_HUMAN_SESSION.remove(id);
                ONLINE_ROLE_SESSION.remove(socket);
                System.out.println("会话失效,已剔除无效人物:ID=" + id);
            }
        }
    }
}
